const lodash = require('lodash')

function selectWhere(tableName, where, limit, order) {
    let sql = 'select * from ' + tableName
    if (where) {
        sql = sql + " " + where
    }
    if (order) {
        sql = sql + " " + order
    }
    if (limit) {
        sql = sql + " " + limit
    }
    return sql
}

function sqlWhere(sql, where, limit, order) {
    if (where) {
        sql = sql + " " + where
    }
    if (order) {
        sql = sql + " " + order
    }
    if (limit) {
        sql = sql + " " + limit
    }
    return sql
}

function dictToWhere(dict) {
    if (lodash.isEmpty(dict) || lodash.isUndefined(dict)) {
        return ""
    }
    let keys = Object.keys(dict)
    let fields = []
    for (let key of keys) {
        let value = dict[key]
        if (lodash.isString(value)) {
            let trimValue = lodash.trim(value)
            if (trimValue.startsWith("=") || trimValue.startsWith("!=")) {
                fields.push(key + " " + trimValue)
            } else {
                fields.push(key + ' = "' + value + '"')
            }
        } else if (lodash.isArray(value)) {
            if (value.length == 1) {
                if (lodash.isString(value[0])) {
                    fields.push(key + ' = "' + value[0] + '"')
                } else {
                    fields.push(key + ' = ' + value[0])
                }
            } else if (value.length > 1) {
                let str = value.join(",")
                fields.push(key + ' in (' + str + ')')
            }
        } else {
            if (value != -1) {
                fields.push(key + ' = ' + value)
            }
        }
    }
    if (fields.length > 0) {
        return 'where ' + fields.join(" and ")
    }
    return ""
}

export { sqlWhere, selectWhere, dictToWhere }